package com.txy.servlet;

import com.txy.entity.User;
import com.txy.exception.LoginErrorException;
import com.txy.service.UserService;
import com.txy.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author：汤小洋
 * Date：2022-11-08 13:52
 * Description：<描述>
 */
@WebServlet("*.user")
public class UserServlet extends HttpServlet {

    UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取Servlet路径
        String path = req.getServletPath();
        if ("/login.user".equals(path)) {
            login(req, resp);
        } else if ("/register.user".equals(path)) {
            register(req, resp);
        }else if("/logout.user".equals(path)){
            logout(req,resp);
        }
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.getSession().invalidate();
        resp.sendRedirect("index.jsp");
    }


    /**
     * 用户登陆
     */
    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        try {
            User user = userService.login(username, password);
            req.getSession().setAttribute("user",user);

            req.getRequestDispatcher("/WEB-INF/pages/manager.jsp").forward(req,resp);
        } catch (LoginErrorException e) {
            req.setAttribute("errorMsg",e.getMessage());
            req.getRequestDispatcher("/index.jsp").forward(req,resp);
        }
    }

    /**
     * 用户注册
     */
    private void register(HttpServletRequest req, HttpServletResponse resp) {
    }


}
